<?php
namespace app\model;

use think\Db;

class UserOrder extends Common
{
    protected static $obj;

    public function _initialize()
    {
        parent::_initialize();
        $this->db_name = 'user_order';
    }

    /**
     * 类入口
     * @return UserOrder
     */
    public static function getInstance()
    {
        if (is_null(self::$obj))
            self::$obj = new self();
        return self::$obj;
    }

    /**
     * 验证id
     * @param $int_question_id int 用户地址id
     * @return bool
     */
    public function checkOrderId($int_order_id)
    {
        $order_id = $this->toValue(['order_id' => $int_order_id], 'order_id');
        if ($order_id > 0) return true;
        return false;
    }

    /*z
     * 订单详情
     *
     */
    public function orderDetail($int_order_id,$courierId)
    {
        $field = 'u.package,u.order_state as orderState,u.received_lng as receivedLng,u.received_lat as receivedLat,u.delivery_time as deliveryTime,
        u.order_sn as orderSn,u.door_time as doorTime,u.order_amount as orderAmount,u.first_heavy_fee as firstFee,u.other_heavy_fee as otherFee,
        u.recipient_info as recipientInfo,u.sender_info as senderInfo,u.item_weight as itemWeight,u.item_price as itemPrice,
        u.item_type as itemType,u.protect_price as protectPrice,u.express_order_sn as expressOrderSn,u.item_type_id as itemTypeId,u.express_logo as expressLogo,
        u.is_print as isPrint,u.clear_type as clearType,u.clear_reason as clearReason,u.gmt_create as userCreateTime,u.express_name as expressName,
        courier_order.arrive_time as arriveTime,courier_order.collect_time as collectTime,
        courier_order.complete_time as completeTime,courier_order.gmt_create as courierPickTime';

        $data = Db::name($this->db_name)
            ->alias('u')
            ->join('courier_order','courier_order.order_id = u.order_id')
            ->where(['u.order_id'=>$int_order_id,'courier_order.courier_id'=>$courierId])
            ->field($field)
            ->find();
//        echo Db::name('')->getLastSql();
        return $data;

    }

    /*
     * 我的订单
     * type:1:未取件；2：已取件；3待配送
     */
    public function myOrder($int_courier_id,$type)
    {
        switch ($type){
            case 1 :
                $where_arr['courier_order.state'] = ['in',['0','70','20']];
                $field = 'a.order_id as orderId,a.recipient_info,a.sender_info,a.door_time,a.send_lng as lng,a.send_lat as lat,package,a.order_state';
                break;
            case 2 :
                $where_arr['courier_order.state'] = ['in',['25','30']];
                $field = 'a.order_id as orderId,a.sender_info,courier_order.arrive_time as arriveTime,a.order_sn,a.order_state,a.is_print,package';
                break;
            case 3 :
                $where_arr['courier_order.state'] = '75';
                $field = 'a.order_id as orderId,a.recipient_info,a.express_order_sn,a.received_lng as lng,a.received_lat as lat,package,a.order_state';
                break;
            default:
                _returnError(10014);
                break;
        }
        $where_arr['courier_order.courier_id'] = $int_courier_id;
        $data = Db::name($this->db_name)
            ->alias('a')
            ->join('courier_order','a.order_id= courier_order.order_id')
            ->field($field)
            ->order('courier_order.gmt_create desc')
            ->where($where_arr)
            ->select();
//        echo Db::name($this->db_name)->getlastsql();
        return $data;

    }

    /*
    * 快递员待抢订单
    * toGrabTheOrder
    */
    public function toGrabTheOrder($courierAreaId,$deliveryId,$type){

        switch ($type){
            case 1: //收件单
                $where['order_state'] = 10;
                $where['send_area_id'] = $courierAreaId;
                $field = 'order_id as orderId,door_time as doorTime,recipient_info as recipientInfo,sender_info as senderInfo,send_lat as sendLat,send_lng as sendLng';
                $list = Db::name($this->db_name)
                    ->where($where)
                    ->field($field)
                    ->select();
                $listCount = Db::name($this->db_name)
                    ->where($where)
                    ->field($field)
                    ->count();
                $data['list'] = $list;
                $data['listCount'] = $listCount;

                break;
            case 2: //派件单
                $where['station_order.state'] = 60;
                $where['station_info.area_id'] = $deliveryId;
                $field = 'u.express_order_sn as expressSn,u.order_id as orderId,u.recipient_info as recipientInfo,station_info.address,station_info.lat as sendLat,station_info.lng as sendLng';

                $list = Db::name($this->db_name)
                    ->alias('u')
                    ->join('station_order','u.order_id = station_order.order_id')
                    ->join('station_info','station_info.id = station_order.station_id')
                    ->field($field)
                    ->where($where)
                    ->select();
                $listCount =  Db::name($this->db_name)
                    ->alias('u')
                    ->join('station_order','u.order_id = station_order.order_id')
                    ->join('station_info','station_info.id = station_order.station_id')
                    ->where($where)
                    ->count();
                $data['list'] = $list;
                $data['listCount'] = $listCount;
                break;
            default:
                _returnError(15022);
                break;
        }
        return $data;
//        echo Db::name($this->db_name)->getLastSql();

    }
    /*
     * 快递员订单记录
     *
     */
    public function orderRecord($courierId,$firstRow,$listRow){

        $where = [
            'courier_order.courier_id'=>$courierId,
            'courier_order.state' => array('in',['0','40','80','90'])
        ];
        $field = 'u.recipient_info as recipientInfo,u.sender_info as sendInfo,courier_order.complete_time as time,
        courier_order.state as state,courier_order.order_id as orderId';
        $list = Db::name($this->db_name)
            ->alias('u')
            ->join('courier_order','courier_order.order_id = u.order_id')
            ->where($where)
            ->field($field)
            ->order('courier_order.complete_time desc')
            ->limit($firstRow,$listRow)
            ->select();
        $totalCount = Db::name($this->db_name)
            ->alias('u')
            ->join('courier_order','courier_order.order_id = u.order_id')
            ->where($where)
            ->count();
        $data['totalPages'] = ceil($totalCount/$listRow);
        $data['notesList'] = $list;
//        echo Db::name('')->getLastSql();
        return $data;
    }

    /**
     * 会员管理订单列表
     */
    public function getOrderList($arr_where,$int_first_row,$int_list_rows,$sort){
        $data =  Db::name($this->db_name)
            ->where($arr_where)
            ->field('order_id as orderId,user_order.order_sn as orderSn,user_order.express_order_sn as expressOrderSn,user_order.gmt_create as gmtCreate,user_order.order_amount as orderAmount,user_order.pay_type as paytype,user_order.order_state as orderState')
            ->limit($int_first_row,$int_list_rows)
            ->order("user_order.gmt_create $sort")
            ->select();
//        $stateInfo = Db::name($this->db_name)
//            ->where($arr_where)
//            ->field('user_order_log.describe,user_order_log.gmt_create')
//            ->join('user_order_log','user_order_log.order_id=user_order.order_id','left')
//            ->order('user_order_log.gmt_modified','desc')
//            ->group('user_order.order_id')
//            ->select();
//        echo db('')->getlastsql();
        $stateInfo = Db::query("SELECT * FROM (SELECT user_order_log.describe,user_order_log.gmt_create,user_order.order_id as orderId FROM user_order LEFT JOIN  user_order_log ON user_order_log.order_id=user_order.order_id WHERE $arr_where ORDER BY user_order_log.gmt_modified desc) t GROUP BY t.orderId");
        foreach ($data as $key=>$val){
            foreach ($stateInfo as $k=>$v){
                if ($val['orderId']==$v['orderId']){
                    $data[$key]['describe']=$v['describe'];
                }
            }
        }
        return $data;
    }

    /**
     * 订单管理-》会员订单
     */
    public function getUserOrderList($arr_where,$int_first_row,$int_list_rows){
        $data =  Db::name($this->db_name)
            ->where($arr_where)
            ->field('user_order.order_id as orderId,user_order.order_sn as orderSn,user_order.express_order_sn as expressOrderSn,user_order.gmt_create as gmtCreate,user_order.order_amount as orderAmount,user_order.pay_type as paytype,user_order.order_state as orderState,user_info.mobile')
            ->join('user_info','user_order.user_id=user_info.user_id','left')
            ->limit($int_first_row,$int_list_rows)
            ->select();
//        $stateInfo = Db::name($this->db_name)
//            ->where($arr_where)
//            ->field('user_order_log.describe,user_order_log.gmt_create')
//            ->join('user_order_log','user_order_log.order_id=user_order.order_id','left')
//            ->order('user_order_log.gmt_modified','desc')
//            ->group('user_order.order_id')
//            ->select();
//        echo db('')->getlastsql();
        $stateInfo = Db::query("SELECT * FROM (SELECT user_order_log.describe,user_order_log.gmt_create,user_order.order_id as orderId FROM user_order LEFT JOIN  user_order_log ON user_order_log.order_id=user_order.order_id WHERE $arr_where ORDER BY user_order_log.gmt_modified desc) t GROUP BY t.orderId");
        foreach ($data as $key=>$val){
            foreach ($stateInfo as $k=>$v){
                if ($val['orderId']==$v['orderId']){
                    $data[$key]['describe']=$v['describe'];
                }
            }
        }
        return $data;
    }

    /**
     * 下单人信息
     */
    public function getUserOrderInfo($arr_where){
        $data = Db::name($this->db_name)
            ->where($arr_where)
            ->field('user_info.user_id AS userId,user_info.mobile,user_info.real_name AS realName,user_info.nickname,user_info.id_number AS idNumber')
            ->join('user_info','user_info.user_id=user_order.user_id','left')
            ->find();
        return $data;
    }

    /**
     * 新老客户交易构成 - 获取付款人数
     * @param $arr_where
     * @return int
     */
    public function getUserNum($arr_where)
    {
        return count(array_unique(Db::name($this->db_name)->where($arr_where)->column('user_id')));
    }


    /**
     * 新老客户交易构成
     * @param $str_time
     * @return array
     */
    public function paymentTimeUser($str_time)
    {
        return Db::name($this->db_name)->where(['gmt_modified' => ['LT', $str_time]])->column('user_id');
    }

    /**
     * 新老客户交易构成 - 获取付款金额
     * @param $arr_where
     * @return float|int
     */
    public function getUserTotalMoney($arr_where)
    {
        return Db::name($this->db_name)->where($arr_where)->sum('order_amount');
    }

}
